import * as echarts from '../ec-canvas/echarts';
import { 
  getChartDay,
  getChartWeek,
  getChartMonth
} from '../../utils/api/BPLControl';
import userBaseInfoState from '../../stores/userBaseInfo';

Component({
  properties: {
    timeType: {
      type: String,
      value: 'week',
      observer: 'onTimeTypeChanged'
    },
    dateRange: {
      type: String,
      value: ''
    },
    currentDate: {
      type: Object,
      value: null,
      observer: 'onDateChanged'
    }
  },

  data: {
    ec: {
      lazyLoad: true
    },
    chart: null,
    chartData: {
      categories: [],
      systolic: [],
      diastolic: []
    },
    // 时间偏移量：0表示当前，1表示上一个周期，以此类推
    daysAgo: 0,
    weeksAgo: 0,
    monthsAgo: 0
  },

  lifetimes: {
    ready() {
      // 组件准备好后初始化图表
      this.initChart();
      // 加载数据
      this.loadChartData();
    }
  },

  methods: {
    // 时间类型改变
    onTimeTypeChanged(newVal, oldVal) {
      if (newVal !== oldVal) {
        // 切换时间类型时，重置所有计数器为0
        this.setData({
          daysAgo: 0,
          weeksAgo: 0,
          monthsAgo: 0
        });
        
        if (this.chart) {
          this.loadChartData();
        }
      }
    },

    // 日期改变
    onDateChanged(newVal, oldVal) {
      if (newVal && this.chart) {
        this.loadChartData();
      }
    },

    // 时间类型切换
    onTimeTypeChange(e) {
      const type = e.currentTarget.dataset.type;
      this.triggerEvent('timechange', { type });
    },

    // 上一个时间段
    onPrevDate() {
      const timeType = this.properties.timeType;
      
      if (timeType === 'day') {
        this.setData({ daysAgo: this.data.daysAgo + 1 });
      } else if (timeType === 'week') {
        this.setData({ weeksAgo: this.data.weeksAgo + 1 });
      } else if (timeType === 'month') {
        this.setData({ monthsAgo: this.data.monthsAgo + 1 });
      }
      
      this.loadChartData();
      this.triggerEvent('prevdate');
    },

    // 下一个时间段
    onNextDate() {
      const timeType = this.properties.timeType;
      
      if (timeType === 'day') {
        const newDaysAgo = Math.max(0, this.data.daysAgo - 1);
        this.setData({ daysAgo: newDaysAgo });
      } else if (timeType === 'week') {
        const newWeeksAgo = Math.max(0, this.data.weeksAgo - 1);
        this.setData({ weeksAgo: newWeeksAgo });
      } else if (timeType === 'month') {
        const newMonthsAgo = Math.max(0, this.data.monthsAgo - 1);
        this.setData({ monthsAgo: newMonthsAgo });
      }
      
      this.loadChartData();
      this.triggerEvent('nextdate');
    },

    // 加载图表数据
    async loadChartData() {
      try {
        const userInfo = userBaseInfoState.data;
        const patientUid = userInfo?.patientUid;
        
        if (!patientUid) {
          console.error('用户信息不存在');
          return;
        }

        const timeType = this.properties.timeType;
        const daysAgo = this.data.daysAgo;
        const weeksAgo = this.data.weeksAgo;
        const monthsAgo = this.data.monthsAgo;

        console.log('📊 加载图表数据:', { timeType, daysAgo, weeksAgo, monthsAgo, patientUid });

        let apiResponse;
        
        // 根据时间类型调用不同的API
        if (timeType === 'day') {
          apiResponse = await getChartDay({ patientUid, daysAgo });
        } else if (timeType === 'week') {
          apiResponse = await getChartWeek({ patientUid, weeksAgo });
        } else if (timeType === 'month') {
          apiResponse = await getChartMonth({ patientUid, monthsAgo });
        }

        console.log('📊 API响应:', apiResponse);

        if (apiResponse && apiResponse.code === 0 && apiResponse.data) {
          const chartData = this.transformChartData(apiResponse.data, timeType);
          this.setData({ chartData });
          this.updateChartOption();
        } else {
          // 显示空数据
          const emptyData = this.getEmptyChartData(timeType);
          this.setData({ chartData: emptyData });
          this.updateChartOption();
        }
      } catch (error) {
        console.error('❌ 加载图表数据失败:', error);
        const emptyData = this.getEmptyChartData(this.properties.timeType);
        this.setData({ chartData: emptyData });
        this.updateChartOption();
      }
    },

    // 转换图表数据格式
    transformChartData(data, timeType) {
      if (!data || !Array.isArray(data)) {
        return this.getEmptyChartData(timeType);
      }

      const categories = [];
      const systolic = [];
      const diastolic = [];

      data.forEach(item => {
        // 处理日期标签
        if (item.date) {
          const date = new Date(item.date);
          if (timeType === 'day') {
            // 日视图：显示时间
            const hour = date.getHours();
            categories.push(`${hour}:00`);
          } else if (timeType === 'week') {
            // 周视图：显示月-日
            const month = date.getMonth() + 1;
            const day = date.getDate();
            categories.push(`${month}-${day}`);
          } else {
            // 月视图：显示日期
            const day = date.getDate();
            categories.push(`${day}日`);
          }
        } else if (item.label) {
          categories.push(item.label);
        } else {
          categories.push('');
        }

        // 处理数据值
        systolic.push(item.systolic || item.sbp || 0);
        diastolic.push(item.diastolic || item.dbp || 0);
      });

      return {
        categories,
        systolic,
        diastolic
      };
    },

    // 获取空图表数据
    getEmptyChartData(timeType) {
      let categories = [];
      
      if (timeType === 'week') {
        categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      } else if (timeType === 'day') {
        categories = ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'];
      } else {
        for (let i = 1; i <= 31; i++) {
          categories.push(`${i}日`);
        }
      }
      
      return {
        categories,
        systolic: new Array(categories.length).fill(0),
        diastolic: new Array(categories.length).fill(0)
      };
    },

    // 初始化图表
    initChart() {
      this.ecComponent = this.selectComponent('#bpChart');
      if (this.ecComponent) {
        this.ecComponent.init((canvas, width, height, dpr) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          canvas.setChart(chart);
          this.chart = chart;
          
          // 初始化后立即更新图表
          this.updateChartOption();
          if (this._pendingChartUpdate) {
            this._pendingChartUpdate = false;
            this.updateChartOption();
          }
          
          return chart;
        });
      }
    },

    // 更新图表数据
    updateChartData(data) {
      if (data) {
        this.setData({ chartData: data });
        this.updateChartOption();
      }
    },

    // 更新图表配置
    updateChartOption() {
      if (!this.chart) {
        console.warn('图表实例未初始化，延迟更新');
        clearTimeout(this._chartRetryTimer);
        this._pendingChartUpdate = true;
        this._chartRetryTimer = setTimeout(() => this.updateChartOption(), 300);
        return;
      }
      
      const data = this.data.chartData;
      console.log('📊 更新图表数据:', data);
      
      // 确保数据格式正确
      const categories = data.categories || [];
      const systolic = data.systolic || [];
      const diastolic = data.diastolic || [];
      
      // 检查是否有有效数据（非0值）
      const hasValidData = systolic.some(v => v > 0) || diastolic.some(v => v > 0);
      
      if (categories.length === 0) {
        console.warn('⚠️ 图表类别为空');
        return;
      }
      
      if (!hasValidData) {
        console.log('ℹ️ 图表数据全为0，显示空状态');
      }
      
      const option = {
        color: ['#006EDB', '#28C7C2'],
        grid: {
          left: 40,
          right: 30,
          top: 30,
          bottom: 50,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.7)',
          borderColor: 'transparent',
          textStyle: {
            color: '#fff',
            fontSize: 12
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(item => {
              result += item.marker + ' ' + item.seriesName + ': ' + item.value + ' mmHg<br/>';
            });
            return result;
          }
        },
        xAxis: {
          type: 'category',
          data: categories,
          boundaryGap: false,
          axisLine: { 
            show: false 
          },
          axisTick: { 
            show: false 
          },
          axisLabel: {
            color: '#86909C',
            fontSize: 10,
            margin: 12
          }
        },
        yAxis: {
          type: 'value',
          min: hasValidData ? function(value) {
            return Math.max(0, Math.floor(value.min / 10) * 10 - 10);
          } : 0,
          max: hasValidData ? function(value) {
            return Math.ceil(value.max / 10) * 10 + 10;
          } : 200,
          axisLine: { 
            show: false 
          },
          axisTick: { 
            show: false 
          },
          splitLine: {
            lineStyle: {
              color: '#D8DCE4',
              type: 'dashed',
              width: 0.6
            }
          },
          axisLabel: {
            color: '#86909C',
            fontSize: 10
          }
        },
        series: [
          {
            name: '高压(收缩压)',
            type: 'line',
            smooth: true,
            data: systolic,
            showSymbol: true,
            symbolSize: 6,
            symbol: 'circle',
            lineStyle: {
              width: 2,
              color: '#006EDB'
            },
            itemStyle: {
              color: '#006EDB',
              borderColor: '#fff',
              borderWidth: 1
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(0, 110, 219, 0.2)' },
                  { offset: 1, color: 'rgba(0, 110, 219, 0)' }
                ]
              }
            }
          },
          {
            name: '低压(舒张压)',
            type: 'line',
            smooth: true,
            data: diastolic,
            showSymbol: true,
            symbolSize: 6,
            symbol: 'circle',
            lineStyle: {
              width: 2,
              color: '#28C7C2'
            },
            itemStyle: {
              color: '#28C7C2',
              borderColor: '#fff',
              borderWidth: 1
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(40, 199, 194, 0.2)' },
                  { offset: 1, color: 'rgba(40, 199, 194, 0)' }
                ]
              }
            }
          }
        ]
      };
      
      this.chart.setOption(option, true);
      console.log('✅ 图表配置已更新');
    }
  }
});
